package com.liuwish.learn.DesignPattern.DynamicProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Description
 * <p>cglib动态代理
 * </p>
 * DATE 2018/6/25.
 *
 * @author liuweishi.
 */
public class DynamicCglib {
    public static void main(String[] args) {
        CGlibHosee cGlibHosee = new CGlibHosee();
        CGlibHoseeProxy cGlibHoseeProxy = new CGlibHoseeProxy();
        CGlibHosee proxy = (CGlibHosee) cGlibHoseeProxy.bind(cGlibHosee);
        System.out.println(proxy.sayhi());
    }
}

class CGlibHosee {
    public String sayhi() {
        return "Welcome oschina hosee's blog";
    }
}

class CGlibHoseeProxy {
    Object obj;

    public Object bind(final Object target) {
        this.obj = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args,
                                    MethodProxy proxy) throws Throwable {
                System.out.println("I'm proxy!");
                Object res = method.invoke(target, args);
                return res;
            }
        });
        return enhancer.create();
    }

}
